package controller

import (
	"ais-go/app/models"
	"ais-go/app/tools"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
)

type LoginCtl struct {
	db *gorm.DB
}

var Login = LoginCtl{}

func (ctl *LoginCtl) Login(c *gin.Context) {
	var req models.User
	ctl.db = models.Db
	c.ShouldBind(&req)
	var user models.User
	//查找是否有该用户
	ctl.db.Preload("Role.Right").Where("username = ?", req.Username).First(&user)
	if user.Username == "" {
		tools.ErrorResp(c, 500, "用户名或密码错误")
		return
	}

	//判断密码是否正确
	if req.Password != user.Password {
		ctl.db.Model(&user).Update("errCount", user.ErrCount+1)
		tools.ErrorResp(c, 500, "用户名或密码错误")
		return
	}

	if user.Status == 0 {
		tools.ErrorResp(c, 500, "账号已被禁用,请联系管理员")
		return
	}
	//判断错误次数是否超过5次
	if user.ErrCount >= 5 {
		ctl.db.Model(&user).Update("status", 0)
		tools.ErrorResp(c, 500, "账号已被禁用,请联系管理员")
		return
	}

	//登录成功，清空错误次数
	//ctl.db.Model(&user).Update("errCount", 0)
	//ctl.db.Model(&user).Update("loginCount", user.LoginCount+1)
	//更新登录次数和错误次数
	ctl.db.Model(&user).Updates(map[string]interface{}{"errCount": 0, "login_count": user.LoginCount + 1})

	orig := user.Id
	key := "91234567890123456789012345678901"
	token := tools.AesEncrypt(strconv.Itoa(int(orig)), key)
	user.Token = token

	tools.SuccessResp(c, "登录成功", user)
}

func (ctl *LoginCtl) Register(c *gin.Context) {
	ctl.db = models.Db
	var user models.User
	c.ShouldBind(&user)
	//user.CreatedAt = time.Now().Format("2006-01-02 15:04:05")
	//user.UpdatedAt = time.Now().Format("2006-01-02 15:04:05")
	//	判断用户名是否存在
	var user1 models.User
	ctl.db.Where("username = ?", user.Username).First(&user1)
	if user1.Id != 0 {
		tools.ErrorResp(c, 500, "用户名已存在")
		return
	}
	user.Role = []models.Role{{BaseModel: models.BaseModel{Id: 2}}}
	ctl.db.Create(&user)
	tools.SuccessResp(c, "注册成功,等待管理员审核", nil)
}
